package com.sxhalo.fsms.quartz;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

import com.sxhalo.fsms.domain.LogSysRunning;
import com.sxhalo.fsms.service.ILogSysRunningService;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sxhalo.fsms.domain.SysTask;
import com.sxhalo.fsms.service.ISysTaskService;

@Service
public class TaskServiceImpl implements TaskService {

	@Autowired
	private ISysTaskService taskMapper;

	@Autowired
	private ILogSysRunningService logSysRunningService;


	@Autowired
	QuartzManager quartzManager;

	public SysTask get(Long id) {
		return taskMapper.selectByPrimaryKey(id);
	}

	public int update(SysTask task) {
		Timestamp nowtime = new Timestamp(System.currentTimeMillis());
		task.setUpdateTime(nowtime);
		return taskMapper.updateByPrimaryKeySelective(task);
	}

	@Override
	public int remove(Long id) {
		try {
			SysTask task = get(id);
			quartzManager.deleteJob(task);
			return taskMapper.deleteByPrimaryKey(id);
		} catch (SchedulerException e) {
			e.printStackTrace();
			return 0;
		}
	}

	@Override
	public int removeBatch(Long[] ids) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public void initSchedule() throws SchedulerException {
		// 这里获取任务信息数据
		List<SysTask> jobList = taskMapper.findWhereList("", "");
		for (SysTask task : jobList) {
			if ("1".equals(task.getJobStatus())) {
				quartzManager.addJob(task);
			}
		}
	}

	@Override
	public void changeStatus(Long jobId, String jobStatus) throws SchedulerException {
		SysTask task = get(jobId);
		if (task == null) {
			return;
		}


		LogSysRunning log=new  LogSysRunning();
		log.setCreateTime(new Date());
		log.setLogType("定时任务");

		if ("0".equals(jobStatus)) {
			quartzManager.deleteJob(task);
			task.setJobStatus("0");
			log.setOperationData( task.getDescription()+"关闭了");
		} else {
			task.setJobStatus("1");
			quartzManager.addJob(task);
			log.setOperationData( task.getDescription()+"启动了");
		}
		logSysRunningService.insertSelective(log);
		update(task);

	}

	@Override
	public void updateCron(Long jobId) throws SchedulerException {
		SysTask task = get(jobId);
		if (task == null) {
			return;
		}
		if ("1".equals(task.getJobStatus())) {
			quartzManager.updateJobCron(task);
		}
		update(task);

	}

	@Override
	public void run(SysTask task) throws SchedulerException {
		quartzManager.runJobNow(task);
	}

	@Override
	public void stop(SysTask task) throws SchedulerException {
		quartzManager.deleteJob(task);
	}

}
